package jfoo;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTextField;

import jfoo.playlist.Playlist;
import jfoo.playlist.PlaylistList;
import audio.AudioFile;
import database.Database;

public class SearchPanel extends JPanel {
	JTextField searchField;
	Window window;

	public SearchPanel(Window window) {

		super();
		this.window = window;
		this.setBackground(Color.WHITE);
		this.setOpaque(true);
		searchField = new JTextField("");
		searchField.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
		searchField.setBackground(Color.WHITE);
		searchField.setOpaque(true);
		searchField.setPreferredSize(new Dimension(600, 20));
		searchField.setBorder(BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
		this.add(searchField);

		searchField.addKeyListener(new launchSearch());
	}

	class launchSearch implements KeyListener {

		public launchSearch() {

		}

		public void keyTyped(KeyEvent e) {
			String s = searchField.getText();
			if (!s.equals("")){
				ArrayList<AudioFile> arrayListFound= Database.getInstance().search(searchField.getText());
			//	System.out.println(arrayListFound.size());
			
				PlaylistList playlistList = window.getPlaylistList();
				int index = playlistList.containSearchPlaylist();
				if (index != -1){
					Playlist playlist = (Playlist)playlistList.getModel().getElementAt(index);
					playlist.clear();
					playlist.add(arrayListFound);
					playlistList.setPlaylist(index);
				}else{
					Playlist p = new Playlist("Search", arrayListFound);
					playlistList.addPlaylist(p);
				}
				
			}
		}

		public void keyPressed(KeyEvent e) {
		}

		public void keyReleased(KeyEvent e) {

		}

	}

}
